// mysql_test_2.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include "MySQLMan.h"
#include <vector>
#include <string>
#include <iostream>
#include "UUIDGenerator.h"
#include "strCoding.h"


CMySQLMan* mysqlClient;

//读取数据
bool Select(MYSQL_RES* Result, std::vector<std::vector<std::string> >& data)
{
	// 行列数
	int row = mysql_num_rows(Result);
	int field = mysql_num_fields(Result);

	MYSQL_ROW line = NULL;
	line = mysql_fetch_row(Result);

	int j = 0;
	std::string temp;
	std::vector<std::vector<std::string> >().swap(data);
	while (NULL != line)
	{
		std::vector<std::string> linedata;
		for (int i = 0; i < field; i++)
		{
			if (line[i])
			{
				temp = line[i];
				linedata.push_back(temp);
			}
			else
			{
				temp = "";
				linedata.push_back(temp);
			}
		}
		line = mysql_fetch_row(Result);
		data.push_back(linedata);
	}
	return true;
}

int TestRunRead()
{
	while (true)
	{
#if 1
		int nNum = 0;
		std::string strSql = "";
		strSql += "SELECT * FROM tb_menu;";
		MYSQL_RES* pMysqlRes;
		pMysqlRes = mysqlClient->SelectRecord(strSql.c_str());
		//assert(pMysqlRes);
		nNum = mysqlClient->GetFieldNum(pMysqlRes);
		long long nllNum;
		nllNum = mysqlClient->GetRowNum(pMysqlRes);

		std::cout << nNum << std::endl;
		std::cout << nllNum << std::endl;
		std::cout << mysqlClient->GetClientInfo() << std::endl;

		for (size_t i = 0; i < nNum; i++)
		{
			std::cout << mysqlClient->GetFieldName(pMysqlRes, i) << std::endl;
		}

		std::vector<std::vector<std::string> > data;
		bool bRet = false;
		bRet = Select(pMysqlRes, data);
		if (!bRet)
		{
			std::cout << "Select error\n";
			return 0;
		}

		for (std::vector<std::vector<std::string> >::const_iterator iter = data.cbegin(); iter != data.cend(); iter++)
		{
			std::cout << "Hello World!\n";
			for (int i = 0; i < (*iter).size(); i++)
			{
				std::cout << mediakit::strCoding::UTF8ToGB2312((*iter)[i]).c_str() << std::endl;
			}
		}
#endif

		printf("TestRunRead\n");
		Sleep(1000);
	}

	return 0;
}

std::string get_uuid() {
	UUIDGenerator uuid;
	return uuid.GenerateUUID();
}

int TestRunWrite()
{
	while (true)
	{
		std::string strSql = "";
		strSql += "INSERT INTO user_log(id, username, operation, operate_time, operate_des, level, is_success, clientIp, OperationDetails) VALUES ('";
		strSql += get_uuid();
		strSql += "', 'superAdmin', '用户登入', '2024 - 02 - 28 10:26 : 23', '登录成功', '1', '0', '192.168.0.64', NULL);";
		bool flag;

		flag = mysqlClient->InsertRecord(strSql.c_str());

		printf("TestRunWrite\n");
		Sleep(1000);
	}
	return 0;
}

int main()
{
	mysqlClient = new CMySQLMan();

	int bRet = mysqlClient->ConnectDB("192.168.0.185", "root", "Mdkj@db2023", "AC_AQRH_DB");
	if (!bRet) {
		printf("open mysql error");
	}

	CThread thre_read;
	thre_read.Start(TestRunRead);
	CThread thre_write;
	thre_write.Start(TestRunWrite);
	std::cout << "Hello World!\n";
}
